import 'dart:async';
import 'dart:io';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:msal_auth/models/msal_exception.dart';
import 'package:msal_auth/msal_auth.dart';
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
import 'package:sptapp/api/interface/login_api.dart';
import 'package:sptapp/api/request/response_data.dart';
import 'package:sptapp/data/user_info_entity.dart';
import 'package:sptapp/utils/string_tool.dart';
import 'package:sptapp/widget/common_widget.dart';
import '../../basic/base_info.dart';
import '../../config/const.dart';
import '../../moudle/message.dart';
import '../../utils/regex_tool.dart';
import '../../widget/common_dialog.dart';
import '../home/home.dart';
import '../index_drawer_page.dart';

import 'package:flutter/material.dart';
// import 'package:flutter_msal_mobile/flutter_msal_mobile.dart';
// import 'package:flutter_msal_mobile/models/models.dart';



class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {

  StreamSubscription? _loginSubscription;
  bool isAgree = true;
  bool isDisabled = false;
  TextEditingController _mailController = TextEditingController();
  TextEditingController _pwdController = TextEditingController();
  TextEditingController codeController = TextEditingController();
  String mail = '';
  String pwd = '';
  String code = '';
  int loginType = 1; // 1:账号密码登录  2:手机号登录

  Timer? _countdownTimer;
  int _countdownNum = 60;
  late String codeText;
  bool isDone = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    codeText = get_code_btn.tr;
    grade = null;
    // _getAccount();
  }

  _getAccount(){
    // String? mailText = LocalBaseInfo.getAccount();
    // if(mailText!=null){
    //   _mailController.text = mailText!;
    //   mail = mailText;
    // }
    // if(mounted){
    //   setState(() {});
    // }
  }

  _login()async{
    showLoading();
    ResponseData res = await LoginAPI.getUserRegister({
      'username':mail,
      'email':mail
    });
    hideLoading();
    if(res.code == 200){
      if(res.data != null && res.data['isExist'] != null && res.data['isExist'] == true){
        Navigator.of(context).pushNamed('LoginSecPage',arguments: {
          'mail':mail
        });
      }else{
        Navigator.of(context).pushNamed('LoginCodePage',arguments: {
          'mail':mail
        });
      }
    }
    // showLoading();
    // ResponseData res = await LoginAPI.login({
    //   'username':mail,
    //   'password':pwd
    // });
    // hideLoading();
    // if(res.code == 200){
    //   LocalBaseInfo.setToken(res.data['token']);
    //   LocalBaseInfo.setAccount(mail);
    //   Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
    //       settings: const RouteSettings(name: "index"),
    //       pageBuilder:
    //           (BuildContext context, Animation animation,
    //           Animation secondaryAnimation) {
    //         return const DrawerIndexPage();
    //       }), (route) => false);
    // }
  }

  _gmailCodeLogin()async{
    showLoading();
    ResponseData res = await LoginAPI.gmailCodeLogin({
      'username':mail,
      'captcha':code
    });
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setToken(res.data['token']);
      LocalBaseInfo.setAccount(mail);
      bool updateUser = res.data['updateUser']?? true;
      if(!updateUser){
        Navigator.of(context).pushNamed('MailRegister',arguments: true);
      }else{
        Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
            settings: const RouteSettings(name: "index"),
            pageBuilder:
                (BuildContext context, Animation animation,
                Animation secondaryAnimation) {
              return const DrawerIndexPage();
            }), (route) => false);
      }
    }
  }

  _loginAPPByApple()async{
    AuthorizationCredentialAppleID appleIdCredential = await SignInWithApple.getAppleIDCredential(
      scopes: [
        AppleIDAuthorizationScopes.email,
        AppleIDAuthorizationScopes.fullName
      ],
    );
    String? identityToken = appleIdCredential.identityToken;
    // final oAuthProvider = OAuthProvider('apple.com');
    print('identityToken ==user ${identityToken.toString()}');
    // final credential = oAuthProvider.credential(
    //   idToken: appleIdCredential.identityToken,
    //   accessToken: appleIdCredential.authorizationCode,
    // );
    if(identityToken != null ){
      _getCodeSignOrLogin('3',identityToken!);
    }
    // try{
    //   print('_loginAPPByApple ==user 123');
    //   final UserCredential? user = (await FirebaseAuth.instance.signInWithCredential(credential));
    //   print('_loginAPPByApple ==user ${user.toString()}');
    //   if(identityToken != null){
    //
    //   }
    // }catch(e){
    //   print('error == '+e.toString());
    // }
  }

  _loginAPPByGoogle()async{
    const List<String> scopes = <String>[
      'email',
    ];
    GoogleSignIn _googleSignIn = GoogleSignIn(
      scopes: scopes
    );
    GoogleSignInAccount? account = await _googleSignIn.signIn();

    GoogleSignInAuthentication? authentication = await account?.authentication;

    StringTool.long_p('authenticationaccessToken ==='+authentication!.accessToken.toString());
    StringTool.long_p('authenticationidToken ==='+authentication!.idToken.toString());
    if(authentication != null && authentication!.idToken != null){
      _getCodeSignOrLogin('1',authentication!.idToken!);
    }

   //  final credential =  GoogleAuthProvider.credential(accessToken: authentication?.accessToken, idToken: authentication?.idToken);
   //
   // UserCredential user = await FirebaseAuth.instance.signInWithCredential(credential);
   //
   //
   //  print('_googleSignIn ==='+user.toString());
  }

  _loginAppByMsal()async{
    // MsalMobileClient msalAuth = await MsalMobileClient.init(
    //   clientId: _clientId,
    //   scopes: _scopes,
    //   androidConfig: AndroidConfig(
    //     configFilePath: 'assets/msal_config.json',
    //     tenantId: _tenantId,
    //   ),
    //   iosConfig: IosConfig(authority: _authority),
    // );
    // try {
    //   final user = await msalAuth.acquireToken();
    //   print('User data: ${user?.toJson()}');
    // } on MsalException catch (e) {
    //   print('Msal exception with error: ${e.errorMessage}');
    // } catch (e) {
    //   print(e.toString());
    // }
    // return;
   getToken();
  }

  Future<MsalAuth> getMsalAuth() async {
    return MsalAuth.createPublicClientApplication(
      clientId: clientId,
      scopes: scopes,
      androidConfig: AndroidConfig(
        configFilePath: 'assets/msal_config.json',
        // tenantId: _tenantId
      ),
      iosConfig: IosConfig(authority: iosAuth,authMiddleware: AuthMiddleware.webView),);
  }
  Future<void> getToken() async {
    try {
      final msalAuth = await getMsalAuth();
      final user = await msalAuth.acquireToken();
      if(user != null){
        _getCodeSignOrLogin('2',user!.idToken);
      }
    } on MsalException catch (e) {
      print('Msal exception with error: ${e.errorMessage}');
    } catch (e) {
      print(e.toString());
    }
  }

  Future<void> getTokenSilently() async {
    try {
      final msalAuth = await getMsalAuth();
      final user = await msalAuth.acquireTokenSilent();
      print('User data: ${user?.toJson()}');
    } on MsalException catch (e) {
      print('Msal exception with error: ${e.errorMessage}');
    } catch (e) {
      print(e.toString());
    }
  }

  /// 获取验证码
  void getMsgCode() async {
    if(mail == null || mail!.isEmpty){
      showToast(mail_hintText.tr);
      return;
    }
    if(validateEmail(mail!) == false){
      showToast(email_input_error.tr);
      return;
    }
    if(_countdownNum != 60){
      return;
    }
    if (mail == null || mail!.isEmpty) {
      showToast(mail_hintText.tr);
      return;
    }
    showLoading();
    ResponseData res = await LoginAPI.sendEmailLogin(mail!);
    hideLoading();
    if (res.code == 200) {
      startCountDownTimer();
    }
  }

  /// 开始倒计时
  startCountDownTimer() {
    if(_countdownTimer != null){
      _countdownTimer?.cancel();
      _countdownTimer = null;
      _countdownNum = 60;
      codeText = get_code_btn.tr;
    }
    _countdownTimer = Timer.periodic(new Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownNum > 0) {
          codeText = "${_countdownNum--}s";
        } else {
          _countdownTimer?.cancel();
          _countdownTimer = null;
          _countdownNum = 60;
          codeText = get_code_btn.tr;
        }
      });
    });
  }

  getIsDone(){
    if(mail == null || mail!.isEmpty ){
      isDone = false;
    }else{
      isDone = true;
    }
    if(mounted){
      setState(() {});
    }
  }

  _getCodeSignOrLogin(String loginType,String token)async{
    //google,microsoft,apple
    Map<String,dynamic> data = {
      'loginType':loginType,
      'token':token
    };
    showLoading();
    ResponseData res = await LoginAPI.getCodeSignOrLogin(data);
    hideLoading();
    if(res.code == 200){
      LocalBaseInfo.setToken(res.data['token']);
      bool updateUser = res.data['updateUser']?? true;
      if(!updateUser){
        Navigator.of(context).pushNamed('MailRegister',arguments: true);
      }else{
        Navigator.pushAndRemoveUntil(context, PageRouteBuilder(
            settings: const RouteSettings(name: "index"),
            pageBuilder:
                (BuildContext context, Animation animation,
                Animation secondaryAnimation) {
              return const DrawerIndexPage();
            }), (route) => false);
      }
    }
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _loginSubscription?.cancel();
    _countdownTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: defaultBlackBgColor,
      body: GestureDetector(
        onTap: (){
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: SingleChildScrollView(
          child: Container(
            height: 1.sh,
            alignment: Alignment.topCenter,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                SizedBox(height: 240.w,),
                ClipRRect(
                  child: Image.asset('assets/icon/icon.png',width: 144.w,fit: BoxFit.fitWidth,),
                  borderRadius: BorderRadius.circular(16.w),
                ),
                SizedBox(height: 96.w,),
                //邮箱输入框
                Container(
                  width: 670.w,
                  height: 108.w,
                  padding: EdgeInsets.symmetric(horizontal: 30.w),
                  decoration: BoxDecoration(
                      border: Border.all(color: Color.fromRGBO(255, 255, 255, 0.5),width: 1.w),
                      borderRadius: BorderRadius.circular(20.w)
                  ),
                  child:  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Expanded(child: TextField(
                        //控制器
                        textInputAction: TextInputAction.done,
                        controller: _mailController,
                        maxLines: 1,
                        //是否自动更正
                        autocorrect: true,
                        //是否自动对焦
                        autofocus: false,
                        style: inputStyle,
                        decoration: InputDecoration(
                          contentPadding: const EdgeInsets.symmetric(vertical: 0,horizontal: 0),
                          hintText: mail_hintText.tr,
                          hintStyle: inputHitStyle,
                          counterText: "",
                          border: OutlineInputBorder(
                              borderSide: BorderSide.none),
                        ),
                        onChanged: (val){
                          setState(() {
                            mail = val.trim();
                          });
                        },
                      )
                      ),
                      SizedBox(width: 20.w,),
                      Visibility(visible: mail!=null&&mail!.isNotEmpty,
                        child: GestureDetector(
                          onTap: (){
                            setState(() {
                              _mailController.text = '';
                              mail = '';
                            });
                          },
                          child: Container(
                            child: Image.asset('assets/common/input_close.png',width: 48.w,),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(top: 66.w,),
                  padding: EdgeInsets.symmetric(horizontal: 48.w),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      GestureDetector(
                        onTap: (){
                          FocusScope.of(context).requestFocus(FocusNode());
                          setState(() {
                            isAgree = !isAgree;
                          });
                        },
                        child: Container(
                          child: Image.asset(isAgree?'assets/login/icon_check.png':'assets/login/icon_unchecked.png',width: 36.w,),
                        ),
                      ),
                      SizedBox(width: 32.w,),
                      Expanded(child:  RichText(
                        text: TextSpan(
                            children:
                            [
                              TextSpan(
                                text: privacy_policy_front_text.tr,
                                style: TextStyle(
                                    color: Color(0xff999999),
                                    fontSize: 22.sp
                                ),
                              ),
                              TextSpan(
                                  text: privacy_policy_tk.tr,
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 22.sp
                                  ),
                                  recognizer: TapGestureRecognizer()..onTap = (){
                                    FocusScope.of(context).requestFocus(FocusNode());
                                    Navigator.of(context).pushNamed('WebViewPage',arguments: {'title': privacy_policy_tk.tr,'url':'https://cloud.sptus.com/SPT-TermsofService.html'});
                                  }
                              ),
                              TextSpan(
                                text: privacy_policy_middle_text.tr,
                                style: TextStyle(
                                    color: Color(0xff999999),
                                    fontSize: 22.sp
                                ),
                              ),
                              TextSpan(
                                  text: privacy_policy_ys.tr,
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 26.sp
                                  ),
                                  recognizer: TapGestureRecognizer()..onTap = (){
                                    FocusScope.of(context).requestFocus(FocusNode());
                                    Navigator.of(context).pushNamed('WebViewPage',arguments: {'title': privacy_policy_ys.tr,'url':'https://cloud.sptus.com/SPT-PrivacyPolicy.html'});
                                  }
                              ),
                            ]
                        ),
                        textAlign: TextAlign.left,
                      ))
                    ],
                  ),
                ),
                SizedBox(height: 34.w,),
                GestureDetector(
                  onTap: ()async{
                    FocusScope.of(context).requestFocus(FocusNode());
                    if(mail == null || mail.isEmpty){
                      return;
                    }

                    if(isAgree==false){
                      openCommonDialog(title: alert_waring_title.tr,content: privacy_policy_alert_text.tr,isHead: false,btnText: alert_waring_surebtn_text.tr,
                          callBack: (){
                            setState(() {
                              isAgree = true;
                            });
                            _login();
                          });
                      return;
                    }
                    _login();
                  },
                  child: Container(
                    width: 670.w,
                    height: 108.w,
                    decoration: BoxDecoration(
                        color: mail != null && mail.isNotEmpty ? themeColor:themeDisableColor,
                        borderRadius: BorderRadius.circular(8.w)
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        // Image.asset('assets/login/icon_wechat.png',width: 56.w,),
                        SizedBox(width: 10.w,),
                        Text('Continue'.tr,style: TextStyle(
                            color: Colors.white,
                            fontSize: 28.sp,
                            fontWeight: FontWeight.w600
                        ),)
                      ],
                    ),
                  ),
                ),

                Expanded(child: GestureDetector(
                  onTap: (){
                    getIsDone();
                    FocusScope.of(context).requestFocus(FocusNode());
                  },
                  child: Container(
                    color: Colors.transparent,
                    width: 1.sw,
                  ),
                )),
                //其他登录方式
                Visibility(visible: true,child: Column(
                  children: [
                    Container(
                      padding: EdgeInsets.symmetric(horizontal: 48.w),
                      height: 48.w,
                      child: Stack(
                        children: [
                          Center(child: Container(
                            height: 1.w,
                            width: 540.w,
                            color: Color(0xff484848),
                          ),),
                          Center(
                            child: Container(
                              alignment: Alignment.center,
                              height: 48.w,
                              width: 48.w,
                              decoration: BoxDecoration(
                                  color: Color(0xff484848),
                                  borderRadius: BorderRadius.circular(48.w)
                              ),
                              child: Text('or',style: TextStyle(
                                  color: Color(0xff939393),
                                  fontSize: 24.sp
                              ),),
                            ),
                          )
                        ],
                      ),
                    ),
                    Visibility(visible: true,child: GestureDetector(
                      onTap: ()async{
                        FocusScope.of(context).requestFocus(FocusNode());
                        if(isAgree==false){
                          openCommonDialog(title: alert_waring_title.tr,content: privacy_policy_alert_text.tr,isHead: false,btnText: alert_waring_surebtn_text.tr,
                              callBack: (){
                                _loginAPPByGoogle();
                                setState(() {
                                  isAgree = true;
                                });
                              });
                          return;
                        }
                        _loginAPPByGoogle();
                      },
                      child: Container(
                        margin: EdgeInsets.only(top: 30.w),
                        width: 670.w,
                        height: 108.w,
                        decoration: BoxDecoration(
                            color: Color(0xff2B2B2B),
                            borderRadius: BorderRadius.circular(8.w)
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Image.asset('assets/login/login_google.png',width: 56.w,),
                            SizedBox(width: 10.w,),
                            Text('Google',style: TextStyle(
                                color: Colors.white,
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600
                            ),)
                          ],
                        ),
                      ),
                    ),),
                    Visibility(visible: true,child: GestureDetector(
                      onTap: ()async{
                        FocusScope.of(context).requestFocus(FocusNode());
                        if(isAgree==false){
                          openCommonDialog(title: alert_waring_title.tr,content: privacy_policy_alert_text.tr,isHead: false,btnText: alert_waring_surebtn_text.tr,
                              callBack: (){
                                _loginAppByMsal();
                                setState(() {
                                  isAgree = true;
                                });
                              });
                          return;
                        }
                        _loginAppByMsal();
                      },
                      child: Container(
                        margin: EdgeInsets.only(top: 30.w),
                        width: 670.w,
                        height: 108.w,
                        decoration: BoxDecoration(
                            color: Color(0xff2B2B2B),
                            borderRadius: BorderRadius.circular(8.w)
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Image.asset('assets/login/login_wr.png',width: 56.w,),
                            SizedBox(width: 10.w,),
                            Text('Microsoft',style: TextStyle(
                                color: Colors.white,
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600
                            ),)
                          ],
                        ),
                      ),
                    ),),
                    Visibility(visible: Platform.isIOS,child: GestureDetector(
                      onTap: ()async{
                        FocusScope.of(context).requestFocus(FocusNode());
                        if(isAgree==false){
                          openCommonDialog(title: alert_waring_title.tr,content: privacy_policy_alert_text.tr,isHead: false,btnText: alert_waring_surebtn_text.tr,
                              callBack: (){
                                _loginAPPByApple();
                                setState(() {
                                  isAgree = true;
                                });
                              });
                          return;
                        }
                        _loginAPPByApple();
                      },
                      child: Container(
                        margin: EdgeInsets.only(top: 30.w),
                        width: 670.w,
                        height: 108.w,
                        decoration: BoxDecoration(
                            color: Color(0xff2B2B2B),
                            borderRadius: BorderRadius.circular(8.w)
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            Image.asset('assets/login/login_apple.png',width: 56.w,),
                            SizedBox(width: 10.w,),
                            Text('Apple',style: TextStyle(
                                color: Colors.white,
                                fontSize: 28.sp,
                                fontWeight: FontWeight.w600
                            ),)
                          ],
                        ),
                      ),
                    ),),
                  ],
                ),),
                SizedBox(height: 32.w,),
                Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      GestureDetector(
                        onTap: (){
                          FocusScope.of(context).requestFocus(FocusNode());
                          Navigator.of(context).pushNamed('RegisterPage').then((val){
                            _getAccount();
                          });
                        },
                        child: Container(
                          child: Text('Create an account'.tr,style: TextStyle(
                              color: Color(0xff576EFF),
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),
                        ),
                      ),
                      Container(
                        width: 6.w,
                        height: 6.w,
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(6.w)
                        ),
                        margin: EdgeInsets.symmetric(horizontal: 20.w),
                      ),
                      GestureDetector(
                        onTap: (){
                          FocusScope.of(context).requestFocus(FocusNode());
                          Navigator.of(context).pushNamed('ForgetPwd',arguments: 1).then((val){
                            _getAccount();
                          });
                        },
                        child: Container(
                          child: Text('Fogot your password？'.tr,style: TextStyle(
                              color: Color(0xff576EFF),
                              fontSize: 28.sp,
                              fontWeight: FontWeight.w600
                          ),),
                        ),
                      )
                    ],
                  ),
                ),
                SizedBox(height: ScreenUtil().bottomBarHeight > 0? ScreenUtil().bottomBarHeight+20.w:48.w,),

              ],
            ),
          ),
        ),
      ),
    );
  }
}

